package com.ch3;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author woldier
 * @version 1.0
 * @description 两阶段终止代码实现
 * @date 2023/4/18 16:34
 **/
@Slf4j(topic = "c.Thread")
public class TPThread {
    private Thread thread;

    public void start(Thread t) {
        this.thread = t;
        this.thread.start();
    }

    public void start() {
        Thread t = new Thread(() -> {
            while(true){
                /*判断是否终止*/
                if(Thread.currentThread().isInterrupted()){
                    log.debug("终止善后工作.....");
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                    log.debug("阻塞调用..........");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }

            }
        });
        this.start(t);
    }

    public void stop(){
        thread.interrupt();
    }

    public static void main(String[] args) throws InterruptedException {
        TPThread tpThread = new TPThread();
        log.debug("开始 执行自定义线程");
        tpThread.start();

        TimeUnit.SECONDS.sleep(10);
        log.debug("主动打断");
        tpThread.stop();

    }
}
